use {
    crate::model::dapp_wallet::DAppWallet,
    sqlx::{MySql, Pool, Row},
};

impl DAppWallet {
    pub async fn insert(one: &Self, pool: &Pool<MySql>) -> anyhow::Result<u64> {
        let id = sqlx::query(r#"INSERT INTO dapp_wallet (mnemonic, eth_pr, eth_pk, tron_pr, tron_pk) VALUES (?,?,?,?,?)"#)
            .bind(one.mnemonic.clone())
            .bind(one.eth_pr.clone())
            .bind(one.eth_pk.clone())
            .bind(one.tron_pr.clone())
            .bind(one.tron_pk.clone())
            .execute(pool)
            .await?
            .last_insert_id();
        Ok(id)
    }

    pub async fn select_all(pool: &Pool<MySql>) -> anyhow::Result<Vec<DAppWallet>> {
        let rows = sqlx::query(r#"SELECT * FROM dapp_wallet order by id desc"#)
            .fetch_all(pool)
            .await?;

        let mut list = Vec::new();
        for row in rows {
            let id = row.get::<u64, _>("id");
            let mnemonic = row.get::<String, _>("mnemonic");
            let eth_pr = row.get::<String, _>("eth_pr");
            let eth_pk = row.get::<String, _>("eth_pk");
            let tron_pr = row.get::<String, _>("tron_pr");
            let tron_pk = row.get::<String, _>("tron_pk");
            let aw = DAppWallet {
                id: Some(id),
                mnemonic,
                eth_pr,
                eth_pk,
                tron_pr,
                tron_pk,
            };
            list.push(aw);
        }

        Ok(list)
    }
}
